<!-- 省市二级联动选择器 -->
<template>
  <div>
    <el-select
      v-model="address.province"
      placeholder="Select Province"
      :style="{ width: provinceWidth + 'px' }"
    >
      <el-option
        v-for="item in provinceArr"
        :key="item"
        :label="item"
        :value="item"
      />
    </el-select>
    <el-select
      v-model="address.city"
      placeholder="Select City"
      :style="{ width: cityWidth + 'px' }"
    >
      <el-option
        v-for="item in cityArr"
        :key="item"
        :label="item"
        :value="item"
      />
    </el-select>
  </div>
</template>

<script setup>
import areaObj from '@/assets/public/pc.json';
import { reactive, computed, watch, ref, defineEmits } from "vue";

// 接收父组件传参
const props = defineProps({
  provinceWidth: {
    type: Number,
    default: 160
  },
  cityWidth: {
    type: Number,
    default: 160
  }
});

const address = reactive({
  province: '',
  city: ''
});

const emit = defineEmits(['select']);

// 省
const provinceArr = Object.keys(areaObj);
address.province = ref(provinceArr[0]);

// 市
const cityArr = computed(() => {
  return areaObj[address.province];
});
address.city = ref(cityArr.value[0]);

// 监听省份变化
watch(() => address.province, (newVal) => {
  address.city = areaObj[newVal][0];
  emitSelectedAddress();
});

// 监听市变化
watch(() => address.city, (newVal) => {
  emitSelectedAddress();
});

const emitSelectedAddress = () => {
  emit('select', { ...address });
};
</script>

<style lang="scss" scoped>

</style>
